package com.ruoyi.web.controller.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.domain.BaseReportDay;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.IBaseReportDayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
@EnableScheduling
public class Timer {
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IBaseReportDayService iBaseReportDayService;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    /**
     * 统计每天注册用户
     */
    @Async
    @Scheduled(cron = "0 55 23 * * ?")
    public void generateAppUserRegist() {
        BaseReportDay reportDay = new BaseReportDay();
        reportDay.setCreateTime(new Date());
        reportDay.setType(2L);//类型 1 每日在线人数 2 每日注册用户
        reportDay.setNumber(iAppUserService.count(new QueryWrapper<AppUser>().ge("create_time", DateUtils.getStartTime(new Date()))));
        reportDay.setTimes(new Date());
        iBaseReportDayService.insertBaseReportDay(reportDay);
    }

    /**
     * 统计每天在线
     */
    @Async
    @Scheduled(cron = "0 55 23 * * ?")
    public void generateAppUserOnline() {
        BaseReportDay reportDay = new BaseReportDay();
        reportDay.setCreateTime(new Date());
        reportDay.setType(1L);//类型 1 每日在线人数 2 每日注册用户
        reportDay.setNumber(iAppUserService.count(new QueryWrapper<AppUser>().ge("last_login_time", DateUtils.getStartTime(new Date()))));
        reportDay.setTimes(new Date());
        iBaseReportDayService.insertBaseReportDay(reportDay);
    }

    /**
     * 统计每天在线 设备在线数量
     * ios android  web
     */
    @Async
    @Scheduled(cron = "0 55 23 * * ?")
    public void generateAppUserOnlineForEquipment() {
        BaseReportDay reportDay = new BaseReportDay();
        reportDay.setCreateTime(new Date());
        reportDay.setType(3L);//类型 1 每日在线人数 2 每日注册用户 3 每日在线人数-android  4 每日在线人数-ios  5 每日在线人数-web
        reportDay.setNumber(iAppUserService.count(new QueryWrapper<AppUser>()
                .eq("equipment", "android")
                .ge("last_login_time", DateUtils.getStartTime(new Date()))));
        reportDay.setTimes(new Date());
        iBaseReportDayService.insertBaseReportDay(reportDay);

        reportDay.setCreateTime(new Date());
        reportDay.setType(4L);//类型 1 每日在线人数 2 每日注册用户 3 每日在线人数-android  4 每日在线人数-ios  5 每日在线人数-web
        reportDay.setNumber(iAppUserService.count(new QueryWrapper<AppUser>()
                .eq("equipment", "ios")
                .ge("last_login_time", DateUtils.getStartTime(new Date()))));
        reportDay.setTimes(new Date());
        iBaseReportDayService.insertBaseReportDay(reportDay);

        reportDay.setCreateTime(new Date());
        reportDay.setType(5L);//类型 1 每日在线人数 2 每日注册用户 3 每日在线人数-android  4 每日在线人数-ios  5 每日在线人数-web
        reportDay.setNumber(iAppUserService.count(new QueryWrapper<AppUser>()
                .eq("equipment", "web")
                .ge("last_login_time", DateUtils.getStartTime(new Date()))));
        reportDay.setTimes(new Date());
        iBaseReportDayService.insertBaseReportDay(reportDay);
    }

    /**
     * 更新用户在线情况
     */
    @Async
    @Scheduled(cron = "0 */30 * * * ?")
    public void updataUserState() {
        long limit = 500;
        long pageNo = 1;
        Boolean isRunState = true;
        while (isRunState) {
            Page pageobj = iAppUserService.page(new Page<>(pageNo, limit), new QueryWrapper<AppUser>().orderByDesc("create_time"));
            List<AppUser> users = pageobj.getRecords();
            if (users.size() == 0) {
                isRunState = false;
                break;
            }
            pageNo++;
            List<String> userIds = users.stream().map(AppUser::getAccount).collect(Collectors.toList());
            String res = tencentCloudImUtil.queryOnlineStatus(userIds);
            JSONObject resJSON = JSONObject.parseObject(res);
            if (resJSON.getIntValue("ErrorCode") == 0) {
                JSONArray arrayList = resJSON.getJSONArray("QueryResult");
                arrayList.stream().filter(Objects::nonNull).forEach(item -> {
                    String account = ((JSONObject) item).getString("To_Account");
                    AppUser appUser = new AppUser();
                    appUser.setOnlineState(((JSONObject) item).getString("Status"));
                    iAppUserService.update(appUser, new QueryWrapper<AppUser>().eq("account", account));
                });
            }
        }
    }
}
